// 常用组件封装
import Vue from 'vue'
const qnyUpload = require('./qnyUpload.js')

// let zzOne = /^[0-9A-Za-z]+$/;//特殊字符
// let zzTwo = /[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/;//文字加字母
// if(!zzOne.test(this.pswVal)){
// 	this.toast('密码不能含有特殊字符');
// 	return;
// }
// if(!zzTwo.test(this.pswVal)){
// 	this.toast('密码为数字+字母');
// 	return;
// }

// 添加缓存
Vue.prototype.cache = function(key, data) {
	uni.setStorageSync(key, data);
}

// 數字單位
Vue.prototype.numDw = function(key) {
	let num = key;
	if (num >= 1000) {
	    return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
	  }
	return num.toString();
}

// 页面跳转
Vue.prototype.jump = function(url, type) {
	if (type == 1) {
		uni.switchTab({
			url: url
		})
	} else if (type == 2) {
		uni.redirectTo({
			url: url
		});
	} else if (type == 3) {
		// setTimeout(function() {
		uni.reLaunch({
			url: url
		});
		// }, 1000);
	} else if (type == 'back') {
		if (getCurrentPages().length > 1) {
			uni.navigateBack()
		} else {
			uni.navigateTo({
				url: '/pages/tabBar/home'
			})
		}
	} else {
		uni.navigateTo({
			url: url
		})
	}
};

// 无icon的提示框
Vue.prototype.toast = function(cont) {
	uni.showToast({
		title: cont,
		icon: 'none',
		duration: 2500
	})
};

// 返回上一级
Vue.prototype.UpperStrata = function() {
	uni.navigateBack({
		delta: 1
	});
};

// 手机号加密
Vue.prototype.phoneEncryption = function(num) {
	var phone = "" + num;
	return phone.substr(0, 3) + "****" + phone.substr(7);
}

// 验证手机号 --  手机号正则
Vue.prototype.vPhone = function(phone) {
	// const myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
	const myreg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
	if (myreg.test(phone)) {
		return false;
	} else {
		return true;
	}
}

// 复制
Vue.prototype.copyText = function(value) {
	value = String(value)
	uni.setClipboardData({
		//准备复制的数据
		data: value,
		success: function(res) {
			uni.showToast({
				title: '复制成功',
			});
		}
	})
}

// 姓名加密
Vue.prototype.nameEncryption = function(name) {
	let str = '';
	str = name.substring(0, name.length - 1)
	return str + '*'
}

// 预览图片
Vue.prototype._previewImage = function(image) {
	var imgArr = [];
	if (typeof image == 'string') {
		imgArr.push(image);
	} else {
		imgArr = image
	}
	uni.previewImage({
		urls: imgArr,
		current: imgArr[0]
	});
}

// 预览图片2222
Vue.prototype._previewImageT = function(list, i) {
	// var imgArr = [];
	// if (typeof image == 'string') {
	// 	imgArr.push(image);
	// } else {
	// 	imgArr = image
	// }
	uni.previewImage({
		urls: list,
		current: list[i]
	});
}

// 获得当前时间年月日时分秒
Vue.prototype.sjVal = function(val) {
	let str = "";
	let date = new Date();
	let year = date.getFullYear();
	let month = (date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1));
	let day = date.getDate() > 10 ? date.getDate() : ('0' + date.getDate());
	let hours = date.getHours(); //获取当前小时数(0-23)
	let minute = date.getMinutes(); //获取当前分钟数(0-59)
	let seconds = date.getSeconds(); //获取当前秒数(0-59)
	if (val == 0) { //年月
		str = year + '-' + month;
	} else if (val == 1) { //年月日
		str = year + '-' + month + '-' + day;
	} else if (val == 2) { //时分
		str = hours + ':' + minute;
	} else if (val == 3) { //时分秒
		str = hours + ':' + minute + ':' + seconds;
	} else if (val == 4) { //全部
		str = year + '-' + month + '-' + day + ' ' + hours + ':' + minute + ':' + seconds;
	}
	return str;
}

// 时间转换-------时间戳10位为秒，10位时需time*1000；13位为毫秒
Vue.prototype.timeTransformation = function(time, type) {
	let date = null;
	let str = ''
	if (time) {
		date = new Date(time);
	} else {
		date = new Date()
	}
	let y = date.getFullYear();
	let MM = date.getMonth() + 1;
	MM = MM < 10 ? ('0' + MM) : MM; //月补0
	let d = date.getDate();
	d = d < 10 ? ('0' + d) : d; //天补0
	let h = date.getHours();
	h = h < 10 ? ('0' + h) : h; //小时补0
	let m = date.getMinutes();
	m = m < 10 ? ('0' + m) : m; //分钟补0
	let s = date.getSeconds();
	s = s < 10 ? ('0' + s) : s; //秒补0

	if (type) {
		str = y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s; //年月日时分秒
	} else {
		str = y + '-' + MM + '-' + d; //年月日
	}

	// console.log(str)
	return str
}

// 时间转成前多长时间
Vue.prototype.advanceTime = function(time) {
	let currentTime = new Date(); //当前时间
	let beforeTime = new Date(time); //创建时间
	let str; //返回的字符

	let usedTime = currentTime - beforeTime; // 相差的毫秒数
	let days = Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数
	let leavel = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的时间
	let hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数
	let leavel2 = leavel % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
	let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
	str = days + '天' + hours + '时' + minutes + '分'
	if (minutes == 0 && hours == 0) {
		str = '刚刚'
	} else if (hours == 0) {
		str = minutes + '分钟前'
	} else if (days == 0) {
		str = hours + '小时前'
	} else if (days > 0 && days < 3) {
		str = days + '天前'
	} else {
		str = time
	}
	return str
}

// 验证身份证  -- 身份证正则
Vue.prototype.vIdentityCode = function(id) {
	const myreg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
	if (myreg.test(id)) {
		return false
	} else {
		return true
	}
}

// 导航到某地(调用第三方地图软件)
Vue.prototype.navigation = function(latitude, longitude, name) {
	//#ifdef APP-PLUS
	let url = "";
	if (plus.os.name == "Android") { //判断是安卓端
		plus.nativeUI.actionSheet({ //选择菜单
			title: "选择地图应用",
			cancel: "取消",
			buttons: [{
				title: "腾讯地图"
			}, {
				title: "百度地图"
			}, {
				title: "高德地图"
			}]
		}, function(e) {
			switch (e.index) {
				//下面是拼接url,不同系统以及不同地图都有不同的拼接字段
				case 1:
					//注意referer=xxx的xxx替换成你在腾讯地图开发平台申请的key
					url =
						`qqmap://map/geocoder?coord=${latitude},${longitude}&referer=I47BZ-QPEWO-HIPWK-SA5DW-F6ZRE-O2FCO`;
					break;
				case 2:
					url =
						`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
					break;
				case 3:
					url =
						`androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
					break;
				default:
					break;
			}
			if (url != "") {
				url = encodeURI(url); //plus.runtime.openURL(url,function(e){})调起手机APP应用
				plus.runtime.openURL(url, function(e) {
					plus.nativeUI.alert("本机未安装指定的地图应用");
				});
			}
		})
	} else {
		//     iOS上获取本机是否安装了百度高德地图，需要在manifest里配置
		//     在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
		//      (如urlschemewhitelist:["iosamap","baidumap"])
		//      uniapp 里配置
		//      "ios" : {
		//           // "urlschemewhitelist":["iosamap","baidumap"]
		//      },
		plus.nativeUI.actionSheet({
			title: "选择地图应用",
			cancel: "取消",
			buttons: [{
				title: "腾讯地图"
			}, {
				title: "百度地图"
			}, {
				title: "高德地图"
			}]
		}, function(e) {
			switch (e.index) {
				case 1:
					url =
						`qqmap://map/geocoder?coord=${latitude},${longitude}&referer=I47BZ-QPEWO-HIPWK-SA5DW-F6ZRE-O2FCO`;
					break;
				case 2:
					url =
						`baidumap://map/markerlocation=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
					break;
				case 3:
					url =
						`iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
					break;
				default:
					break;
			}
			if (url != "") {
				url = encodeURI(url);
				plus.runtime.openURL(url, function(e) {
					plus.nativeUI.alert("本机未安装指定的地图应用");
				});
			}
		})


	}
	//#endif
}

// 打电话
Vue.prototype.contact = function(phone) {
	// 参考官网
	uni.makePhoneCall({
		phoneNumber: phone
	})
}

// 七牛云图片上传
Vue.prototype.uploadFile = function(filePath, utoken, url, bucket,key) {
	var promise = new Promise((resolve, reject) => {
		// console.log('七牛云上传',qnyUpload.upload(filePath));
		qnyUpload.upload(filePath,
			(res) => {
				resolve(res)
			},
			(error) => {
				reject(error)
			}, {
				region: 'SCN',
				uploadUrl: url,
				domain: '',
				bucket: bucket,
				uptoken: utoken,
				key:key
			}
		)
	})
	return promise;
}